export const knowledgeAccess = (obj: any, session: any) => {
  const { showAgentIds = [], editAgentIds = [], showDepartmentIds = [], editDepartmentIds = [], showPeerIds = [], editPeerIds = [] } = obj || {}
  if (
    [showAgentIds, editAgentIds, showDepartmentIds, editDepartmentIds, showPeerIds, editPeerIds].every(i => !i.length) ||
      session.user.type === 1 || // 1和2为admin
      session.user.type === 2
  ) { // 没有编辑的数据默认有可编辑可看权限
    return {
      canEdit: true,
      canShow: true
    }
  }
  const { _id, user } = session
  const departmentList = user?.departmentConfig?.departmentIdList || []
  const peerIds = user?.queueList || []
  return {
    canEdit:
        editAgentIds.includes(_id) ||
        editDepartmentIds.some(i => departmentList.includes(i)) ||
        editPeerIds.some(i => peerIds.includes(i)),
    canShow:
        showAgentIds.includes(_id) ||
        showDepartmentIds.some(i => departmentList.includes(i)) ||
        showPeerIds.some(i => peerIds.includes(i))
  }
}

export const getNewSession = (session: any, obj: any) => {
  const res = JSON.parse(JSON.stringify(session))
  const { editDepartmentIds = [], showDepartmentIds = [], editPeerIds = [], showPeerIds = [] } = obj
  const departmentIds = [...editDepartmentIds, showDepartmentIds]
  const peerIds = [...editPeerIds, showPeerIds]
  const { departmentConfig, queueList } = res.user
  if (departmentConfig?.departmentIdList && departmentIds) {
    const origin = res.user.departmentConfig.departmentIdList
    res.user.departmentConfig.departmentIdList = [
      ...origin,
      ...departmentIds.filter(i => !origin.includes(i))
    ]
  }
  if (queueList && peerIds) {
    const origin = res.user.queueList
    res.user.queueList = [
      ...origin,
      ...peerIds.filter(i => !origin.includes(i))
    ]
  }
  return res
}
